package be.kdg.netpresent;

import java.io.IOException;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

// Suppress warnings about library restrictions
@SuppressWarnings("restriction")

public class Status extends HttpServlet {
	private static final long serialVersionUID = 1L;

	
	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		
		// Set the return-type to html when page is requested
		response.setContentType("text/html");

		// Start the build of the response-page
		PrintWriter out = response.getWriter();
		out.println("<html>");
		out.println("<head><title>NetPresent Server Status</title></head>");
		out.println("<body>");
		
		// Set relevant page-content according to the status of the observed server object.
		if (CheckServer())
		{
			// html code to return when NetPresent Server is active
			out.println("<span style=\"color:green\">NetPresent Server is running!</span>");
			out.println("<br/><br/> Server ip is " + InetAddress.getLocalHost().getHostAddress() + ".");
		}
		else
		{
			// html code to return when NetPresent Server is inactive
			out.println("<span style=\"color:red\">NetPresent Server is not running</span>");
		}
		
		// Finish html-page with some general information.
		out.println("<br/><br/> If you have any problems running NetPresent, check if you have the latest version of <a href=\"http://java.com/nl/download\">Java</a>.");
		out.println("</body>");
		out.println("</html>");
		out.close();
	}

	// Auto-generated doPost-method for processing form input, not needed in this project.
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		
		// TODO Auto-generated method stub
	} 
	
	// Checks if a service with the name NetPresent is found within the RMI registry at
	// port 2021, returns true if so, false if not.
	private boolean CheckServer(){
		boolean bRunning = false;
		try {
			
			//Connect to RMI registry
			Registry register = LocateRegistry.getRegistry("127.0.0.1", 2021);
			
			// Create a list of running RMI services
			String[] services = register.list();
			
			for (int i= 0; i<services.length; i++) {
				String service = services[i];
				
				// Check if service with name NetPresent is found
				if(service.contains("NetPresent"))
				{
					bRunning = true;			
					//System.out.println("NetPresent found in RMI registry");
				}
			}
		} catch (Exception e) {
			//System.out.println("NetPresent not found in RMI registry");
			bRunning = false;
		}
		return bRunning;
	}
}
